
#include "stdafx.h"
#include "tmediasource.h"
#include "tmediasourcefilter.h"

TMediaStream::TMediaStream()
    :m_pSource(0)
{
}

bool TMediaStream::Initialize(TMediaSource* pSource)
{
    CAutoLock lck(&m_csLock);

    if(pSource)
    {
        m_size = pSource->size();
    }
    m_pSource = pSource;
    return true;
}

HRESULT TMediaStream::SetPointer(LONGLONG llPos)
{
    CAutoLock lck(&m_csLock);

    if (m_pSource == 0 || llPos < 0 || llPos > m_size || llPos < 0)
        return E_INVALIDARG;

    long long pos = (long long)llPos;
    m_pSource->seek(pos);
    return S_OK;
}

HRESULT TMediaStream::Read(PBYTE pbBuffer,
    DWORD dwBytesToRead,
    BOOL bAlign,
    LPDWORD pdwBytesRead)
{
    CAutoLock lck(&m_csLock);

    if (m_pSource == 0 || dwBytesToRead > 0x7FFFFFFF)
        return E_INVALIDARG;
    *pdwBytesRead = m_pSource->read(pbBuffer, dwBytesToRead);
    return S_OK;
}

LONGLONG TMediaStream::Size(LONGLONG *pSizeAvailable)
{
    *pSizeAvailable = m_size;
    return m_size;
}

DWORD TMediaStream::Alignment()
{
    return 1;
}

void TMediaStream::Lock()
{
    m_csLock.Lock();
}
void TMediaStream::Unlock()
{
    m_csLock.Unlock();
}

//////////////////////////////////////////////////////////////////////////

TMediaSourceFilter::TMediaSourceFilter(HRESULT *phr) 
    :CAsyncReader( NAME("TMediaSourceFilter\0"), 0, &m_stream, phr )
{
    AddRef();
}

TMediaSourceFilter::~TMediaSourceFilter()
{
}

void TMediaSourceFilter::ClearStream()
{
    m_stream.Initialize(0);
}

bool TMediaSourceFilter::UpdateStream(TMediaSource *pSource, const CMediaType* mediaType)
{
    if(mediaType != NULL)
        m_mt = *mediaType;
    pSource->seek(0);
    return m_stream.Initialize(pSource);
}

void TMediaSourceFilter::OnMediaComplete()
{
    m_OutputPin.EndOfStream();
}